<template>
  <div class="patrol-plan-container">
    <div class="patrol-header">
      <h2>巡更计划</h2>
      <el-select
          v-model="selectedCommunity"
          placeholder="选择小区"
          @change="loadPlans"
          style="width: 200px; margin-right: 10px;"
      >
        <el-option
            v-for="community in communityList"
            :key="community.id"
            :label="community.name"
            :value="community.id"
        ></el-option>
      </el-select>
      <el-button type="primary" @click="addPlan">
        <Plus /> 添加计划
      </el-button>
    </div>

    <el-table
        :data="plans"
        border
        style="width: 100%;"
        v-loading="loading"
    >
      <el-table-column prop="planName" label="计划名称" width="150" />
      <el-table-column prop="communityName" label="所属社区" width="150" />
      <el-table-column prop="startTime" label="开始时间" width="180" />
      <el-table-column prop="endTime" label="结束时间" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag
              :type="scope.row.status === 1 ? 'success' : (scope.row.status === 0 ? 'info' : 'danger')"
          >
            {{ scope.row.status === 1 ? '进行中' : (scope.row.status === 0 ? '未开始' : '已结束') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="关联路线" width="150">
        <template #default="scope">
          <!-- 增加空值检查 -->
          {{ scope.row.routes && scope.row.routes.length > 0
            ? scope.row.routes.map(r => r.routeName).join(',')
            : '未关联' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="editPlan(scope.row)"
              style="margin-right: 5px;"
          >
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="deletePlan(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑计划弹窗 -->
    <el-dialog
        title="巡更计划信息"
        :visible.sync="dialogVisible"
        width="600px"
    >
      <el-form
          :model="formData"
          ref="formRef"
          label-width="120px"
          :rules="formRules"
      >
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="formData.planName" />
        </el-form-item>
        <el-form-item label="所属社区" prop="communityId">
          <el-select v-model="formData.communityId" placeholder="请选择社区">
            <el-option
                v-for="community in communityList"
                :key="community.id"
                :label="community.name"
                :value="community.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划时间" prop="planTime">
          <el-date-picker
              v-model="formData.planTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="关联路线" prop="routeIds">
          <el-select
              v-model="formData.routeIds"
              multiple
              placeholder="请选择路线"
              collapse-tags
          >
            <el-option
                v-for="route in routeList"
                :key="route.routeId"
                :label="route.routeName"
                :value="route.routeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="0">未开始</el-radio>
            <el-radio label="1">进行中</el-radio>
            <el-radio label="2">已结束</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePlan">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getPlanByCommunity,
  addPlan,
  updatePlan,
  deletePlan as deletePlanApi
} from '../api/patrolPlan'
import { getRouteByCommunity } from '../api/patrolRoute'

export default {
  name: 'PatrolPlan',
  components: {
    Plus
  },
  setup() {
    // 社区列表
    const communityList = ref([
      { id: 1, name: '万象城' },
      { id: 2, name: '万达文旅城' },
      { id: 3, name: '碧桂园' }
    ])

    // 路线列表
    const routeList = ref([])

    // 响应式数据
    const selectedCommunity = ref(1)
    const plans = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const formRef = ref(null)

    // 表单数据
    const formData = reactive({
      planId: null,
      planName: '',
      communityId: null,
      planTime: [],
      routeIds: [],
      status: '0'
    })

    // 表单验证规则
    const formRules = reactive({
      planName: [
        { required: true, message: '请输入计划名称', trigger: 'blur' }
      ],
      communityId: [
        { required: true, message: '请选择所属社区', trigger: 'change' }
      ],
      planTime: [
        { required: true, message: '请选择计划时间', trigger: 'change' }
      ],
      routeIds: [
        { required: true, message: '请至少选择一条路线', trigger: 'change' }
      ]
    })

    // 加载路线列表
    const loadRouteList = async () => {
      try {
        let {data:data} = await getRouteByCommunity(selectedCommunity.value)
        console.log(data)
        if (data.code === 0) {
          routeList.value = data.data
        } else {
          ElMessage.error(data.message || '加载路线失败')
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试')
        console.error('加载路线失败:', error)
      }
    }

    // 加载计划数据
    const loadPlans = async () => {
      try {
        loading.value = true
        let {data:data} = await getPlanByCommunity(selectedCommunity.value)
        console.log(data)
        if (data.code === 0) {
          // 处理可能的空值
          plans.value = data.data.map(plan => ({
            ...plan,
            routes: plan.routes || []  // 如果 routes 为 undefined，设置为空数组
          }))
        } else {
          ElMessage.error(data.message || '加载计划失败')
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试')
        console.error('加载计划失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 添加计划
    const addPlan = () => {
      isEdit.value = false
      formData.planId = null
      formData.planName = ''
      formData.communityId = selectedCommunity.value
      formData.planTime = []
      formData.routeIds = []
      formData.status = '0'
      dialogVisible.value = true

      // 加载路线列表
      loadRouteList()
    }

    // 编辑计划
    const editPlan = (row) => {
      isEdit.value = true
      formData.planId = row.planId
      formData.planName = row.planName
      formData.communityId = row.communityId
      formData.planTime = [row.startTime, row.endTime]

      // 增加空值检查
      formData.routeIds = (row.routes || []).map(r => r.routeId)

      formData.status = row.status.toString()
      dialogVisible.value = true

      // 加载路线列表
      loadRouteList()
    }

    // 删除计划
    const deletePlan = async (row) => {
      try {
        await ElMessageBox.confirm(
            `确定要删除计划 "${row.planName}" 吗？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        )

        let {data:data} = await deletePlanApi(row.planId)
        console.log(data)
        if (data.code === 0) {
          ElMessage.success('删除成功')
          loadPlans()
        } else {
          ElMessage.error(data.message || '删除失败')
        }
      } catch (error) {
        // 如果是取消操作，不显示错误信息
        if (error !== 'cancel') {
          ElMessage.error('网络错误，请稍后重试')
          console.error('删除失败:', error)
        }
      }
    }

    // 保存计划
    const savePlan = async () => {
      // 表单验证
      formRef.value.validate((valid) => {
        if (!valid) return false

        // 准备提交数据
        const submitData = {
          plan: {
            planId: formData.planId,
            planName: formData.planName,
            communityId: formData.communityId,
            startTime: formData.planTime[0],
            endTime: formData.planTime[1],
            status: parseInt(formData.status)
          },
          routeIds: formData.routeIds
        }

        const saveMethod = isEdit.value ? updatePlan : addPlan
        const actionName = isEdit.value ? '更新' : '添加'

        saveMethod(submitData)
            .then(res => {
              if (res.code === 200) {
                ElMessage.success(`成功`)
                dialogVisible.value = false
                loadPlans()
              } else {
                ElMessage.error(res.message)
              }
            })
            .catch(error => {
              ElMessage.error('网络错误，请稍后重试')
              console.error(res.error, error)
          })
      })
    }


    onMounted(() => {
      loadPlans()
    })

    return {
      communityList,
      selectedCommunity,
      routeList,
      plans,
      loading,
      dialogVisible,
      formData,
      formRules,
      formRef,
      loadPlans,
      addPlan,
      editPlan,
      deletePlan,
      savePlan
    }
  }
}

</script>

<style scoped>
.patrol-plan-container {
  padding: 20px;
}

.patrol-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.patrol-header h2 {
  margin-right: 20px;
}
</style>